﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Collections;
using System.Xml;

namespace Bxas.Generator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string cs = string.Empty;
        string crdr = Directory.GetCurrentDirectory();
        int nodeCount = 0;

        public class ListItem
        {
            private string id = string.Empty;
            private string name = string.Empty;
            private string conStr = string.Empty;
            private string fileName = string.Empty;
            private string directoryName = string.Empty;
            public ListItem(string sid, string sname, string sconStr, string sfilename, string sdirectoryname) { id = sid; name = sname; conStr = sconStr; fileName = sfilename; directoryName = sdirectoryname; }
            public ListItem() { }
            public override string ToString() { return this.name; }
            public string ID { get { return this.id; } set { this.id = value; } }
            public string Name { get { return this.name; } set { this.name = value; } }
            public string ConStr { get { return this.conStr; } set { this.conStr = value; } }
            public string FileName { get { return this.fileName; } set { this.fileName = value; } }
            public string DirectoryName { get { return this.directoryName; } set { this.directoryName = value; } }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = crdr.Replace("bin\\Debug", "Templates");

            LoadAgain();
        }

        private void LoadAgain()
        {
            comboBox1.Items.Clear();

            IList list = ProjectList.GetProjectList();

            nodeCount = list.Count;

            for (int i = 0; i < list.Count; i++)
            {
                ListItem item = new ListItem()
                {
                    ID = ((DataView)list)[i][0].ToString(),
                    Name = ((DataView)list)[i][1].ToString(),
                    ConStr = ((DataView)list)[i][2].ToString(),
                    FileName = ((DataView)list)[i][3].ToString(),
                    DirectoryName = ((DataView)list)[i][4].ToString()
                };
                this.comboBox1.Items.Add(item);
            }
            this.comboBox1.DisplayMember = "Name";
            this.comboBox1.ValueMember = "ID";

            comboBox1.Items.Insert(0, new ListItem("0", "Seçiniz", "", "", ""));
            comboBox1.Items.Insert(1, new ListItem("500", "Yeni Kayıt", "", "", ""));

            comboBox1.SelectedIndex = 0;
            textBox1.Text = "";
            textBox2.Text = "";
            listBox1.Items.Clear();
        }

        private void btnTestConn_Click(object sender, EventArgs e)
        {
            cs = textBox1.Text;
            try
            {
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    conn.Open();
                    MessageBox.Show("Bağlantı başarılı", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch { MessageBox.Show("Bağlantı yapılamadı", "UYARI", MessageBoxButtons.OK, MessageBoxIcon.Warning); }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            cs = textBox1.Text;
            try
            {
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    conn.Open();
                    DataTable oAllTables = GetTables();
                    for (int i = 0; i < oAllTables.Rows.Count; i++)
                        listBox1.Items.Add(oAllTables.Rows[i]["TABLE_NAME"].ToString());
                }
            }
            catch { MessageBox.Show("Bağlantı yapılamadı", "UYARI", MessageBoxButtons.OK, MessageBoxIcon.Warning); }

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            listBox1.Items.Clear();

            if (comboBox1.SelectedIndex == 0)
            {
                btnTestConn.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
                label1.Enabled = false;
                label2.Enabled = false;
                label3.Enabled = false;
                label4.Enabled = false;
                label5.Enabled = false;
                textBox1.Enabled = false;
                textBox2.Enabled = false;
                textBox3.Enabled = false;
                textBox4.Enabled = false;
                button5.Enabled = false;
                button6.Enabled = false;
            }
            else
            {
                btnTestConn.Enabled = true;
                button3.Enabled = true;
                label1.Enabled = true;
                label2.Enabled = true;
                label3.Enabled = true;
                label4.Enabled = true;
                label5.Enabled = true;
                textBox1.Enabled = true;
                textBox2.Enabled = true;
                textBox3.Enabled = true;
                textBox4.Enabled = true;
                button5.Enabled = true;
                button6.Enabled = true;

                if (comboBox1.SelectedIndex != 1)
                {
                    ListItem li = (ListItem)comboBox1.SelectedItem;

                    textBox1.Text = li.ConStr;
                    textBox2.Text = li.Name;
                    textBox4.Text = li.FileName;
                    textBox3.Text = li.DirectoryName;
                    button4.Enabled = true;
                }
            }
        }

        //Yeni kayıt - güncelle
        private void button3_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == 1)
            {
                Project p = new Project();
                p.ConStr = textBox1.Text;
                p.Name = textBox2.Text;
                p.FileName = textBox4.Text;
                p.DirectoryName = textBox3.Text;
                nodeCount++;
                p.ID = (nodeCount).ToString();
                ProjectList.InsertProject(p);

                LoadAgain();
            }
            else
            {
                Project p = new Project();
                p.ConStr = textBox1.Text;
                p.Name = textBox2.Text;
                p.FileName = textBox4.Text;
                p.DirectoryName = textBox3.Text;
                p.ID = ((ListItem)comboBox1.SelectedItem).ID.ToString();
                ProjectList.UpdateProject(p);
            }

            MessageBox.Show("Kayıt işlemi yapılmıştır");
        }

        //Sil
        private void button4_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex != 0 && comboBox1.SelectedIndex != 1)
            {
                string deletedID = ((ListItem)comboBox1.SelectedItem).ID.ToString();
                ProjectList.DeleteProject(deletedID);

                int delId = int.Parse(deletedID);
                IList list = ProjectList.GetProjectList();
                nodeCount--;

                for (int i = delId - 1; i < nodeCount; i++)
                {
                    Project p = new Project();
                    p.Name = ((DataView)list)[i][1].ToString();
                    p.ConStr = ((DataView)list)[i][2].ToString();
                    p.FileName = ((DataView)list)[i][3].ToString();
                    p.DirectoryName = ((DataView)list)[i][4].ToString();
                    p.ID = (delId + 1).ToString();
                    ProjectList.UpdateProject(p, (delId).ToString());
                    delId++;
                }

                LoadAgain();
                MessageBox.Show("Silme işlemi yapılmıştır");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox3.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox4.Text = openFileDialog1.FileName;
            }
        }

        //Generate
        private void button1_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

            StreamReader objStreamReader = File.OpenText(textBox4.Text);
            String contents = objStreamReader.ReadToEnd();
            objStreamReader.Close();
            objStreamReader.Dispose();

            LoadDataTypes();

            //DataTable oAllTables = GetTables();
            string TableName = "";

            if (!Directory.Exists(textBox3.Text)) Directory.CreateDirectory(textBox3.Text);

            for (int i = 0; i < listBox1.SelectedItems.Count; i++)
            {
                string tmpcontents = contents;
                TableName = listBox1.SelectedItems[i].ToString();

                StringBuilder FieldsCode = new StringBuilder();
                StringBuilder PropertiesCode = new StringBuilder();
                StringBuilder s_PropertiesCode = new StringBuilder();
                StringBuilder ColumnNames = new StringBuilder();

                string PrimaryKeyName;
                string PrimaryKeyType;

                this.AddColumns(this.GetColumns(TableName), TableName,
                            out FieldsCode,
                            out PropertiesCode,
                            out s_PropertiesCode,
                            out ColumnNames,
                            out PrimaryKeyName,
                            out PrimaryKeyType);

                Dictionary<string, string> paramValues = new Dictionary<string, string>();

                paramValues.Add("PROJECT_NAME", textBox2.Text);
                paramValues.Add("TABLE_NAME", TableName);
                paramValues.Add("FIELDS", FieldsCode.ToString());
                paramValues.Add("PROPERTIES", PropertiesCode.ToString());
                paramValues.Add("STRINGPROPERTIES", s_PropertiesCode.ToString());
                paramValues.Add("COLUMNNAMES", ColumnNames.ToString());
                paramValues.Add("PRIMARY_KEY_NAME", PrimaryKeyName);
                paramValues.Add("PRIMARY_KEY_TYPE", PrimaryKeyType);

                foreach (string key in paramValues.Keys)
                    tmpcontents = tmpcontents.Replace("#VAL_" + key + "#", paramValues[key]);

                string FileName = textBox3.Text + "\\" + TableName + ".cs";

                if (!WriteToFile(FileName, tmpcontents))
                    MessageBox.Show(TableName + ".cs" + " oluşturulamadı.", "UYARI", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            MessageBox.Show("Generate işlemi tamamlanmıştır");
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
        }

        public ArrayList SqlDataTypes = new ArrayList();

        public struct Tabs
        {
            public const string Namespace = "";
            public const string Class = "\t";
            public const string SubClass = "\t\t";
            public const string Property = "\t\t\t";
            public const string Code = "\t\t\t\t";
            public const string IndentCode = "\t\t\t\t\t";
        }

        private DataTable GetTables()
        {
            DataTable oAllTables = new DataTable();
            DataTable UserTables = new DataTable();
            DataRow NewRow = null;
            try
            {
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    conn.Open();

                    using (SqlCommand cmd = new SqlCommand())
                    {

                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "sp_tables";

                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {

                            da.Fill(oAllTables);
                            UserTables = oAllTables.Clone();

                            foreach (DataRow oRow in oAllTables.Rows)
                            {

                                if (oRow["TABLE_TYPE"].ToString() == "SYSTEM TABLE") { continue; }
                                if (oRow["TABLE_TYPE"].ToString() == "VIEW") { continue; }
                                if (oRow["TABLE_NAME"].ToString() == "dtproperties") { continue; }
                                if (oRow["TABLE_NAME"].ToString() == "sysdiagrams") { continue; }

                                NewRow = UserTables.NewRow();
                                NewRow.ItemArray = oRow.ItemArray;
                                NewRow["TABLE_NAME"] = NewRow["TABLE_NAME"].ToString().Replace(" ", "");
                                UserTables.Rows.Add(NewRow);

                            }
                        }

                    }

                }
            }
            catch (Exception) { throw; }

            return UserTables;
        }

        private void AddColumns(DataTable oTable, string TableName,
                            out StringBuilder FieldsCode,
                            out StringBuilder PropertiesCode,
                            out StringBuilder s_PropertiesCode,
                            out StringBuilder ColumnNames,
                            out string PrimaryKeyName,
                            out string PrimaryKeyType)
        {
            string Column_Name = "";

            string required = "false";
            FieldsCode = new StringBuilder();
            PropertiesCode = new StringBuilder();
            s_PropertiesCode = new StringBuilder();
            ColumnNames = new StringBuilder();
            PrimaryKeyName = string.Empty;
            PrimaryKeyType = string.Empty;

            string dt = "";
            string dv = "";
            string dn = "";

            try
            {
                foreach (DataRow oRow in oTable.Rows)
                {

                    dt = "";
                    dv = "";
                    dn = "";
                    if (oRow["TYPE_NAME"].ToString() == "geography"
                     || oRow["TYPE_NAME"].ToString() == "geometry"
                     || oRow["TYPE_NAME"].ToString() == "hierarchyid")
                        continue;
                    GetDotNetDataType(this.SqlDataTypes, "DataBaseType", oRow["TYPE_NAME"].ToString(), ref dt, ref dn, ref dv);

                    Column_Name = oRow["Column_Name"].ToString().Replace(" ", "");

                    if (IsStandardProperty(Column_Name)) { continue; }



                    if (dt == "Guid")
                    {
                        FieldsCode.AppendLine(Tabs.SubClass + "private " + dt + " " + this.CamelCase(Column_Name) + " = System.Guid.Empty;");
                    }
                    else
                    {
                        FieldsCode.AppendLine(Tabs.SubClass + "private " + dt + " " + this.CamelCase(Column_Name) + " = " + dv);
                    }

                    required = "true";

                    if (oRow["NULLABLE"].ToString() == "1")
                    {
                        required = "false";
                    }

                    PropertiesCode.AppendLine(" ");
                    PropertiesCode.AppendLine(Tabs.SubClass + "///<summary>");
                    PropertiesCode.AppendLine(Tabs.SubClass + "///Required = " + required);
                    PropertiesCode.AppendLine(Tabs.SubClass + "///DBType = " + oRow["TYPE_NAME"].ToString());
                    PropertiesCode.AppendLine(Tabs.SubClass + "///C# Type = " + dt);
                    PropertiesCode.AppendLine(Tabs.SubClass + "///</summary> ");
                    PropertiesCode.AppendLine(Tabs.SubClass + "[ColumnAttributes(\"" + Column_Name + "\"," + required + ",\"" + dt + "\")]");
                    PropertiesCode.AppendLine(Tabs.SubClass + "public " + dt + " " + this.ProperCase(Column_Name));
                    PropertiesCode.AppendLine(Tabs.SubClass + "{");

                    PropertiesCode.AppendLine(Tabs.Property + " get ");
                    PropertiesCode.AppendLine(Tabs.Property + " {");
                    PropertiesCode.AppendLine(Tabs.Property + "    return " + this.CamelCase(Column_Name) + ";");
                    PropertiesCode.AppendLine(Tabs.Property + " }");
                    PropertiesCode.AppendLine(Tabs.Property + " set ");
                    PropertiesCode.AppendLine(Tabs.Property + " { ");

                    if (dt.ToLower() == "string")
                    {
                        PropertiesCode.AppendLine(Tabs.Property + "    string valueTrimmed = value.Trim(); ");
                        PropertiesCode.AppendLine("");
                        PropertiesCode.AppendLine(Tabs.Property + "    if (valueTrimmed != " + this.CamelCase(Column_Name) + ")");
                        PropertiesCode.AppendLine(Tabs.Property + "    { ");
                        PropertiesCode.AppendLine(Tabs.Property + "      " + this.CamelCase(Column_Name) + " = valueTrimmed; ");
                        PropertiesCode.AppendLine(Tabs.Property + "      if (!IsUpdateOrInsert.ContainsKey("+TableName+".ColumnNames."+ this.ProperCase(Column_Name)+"))");
                        PropertiesCode.AppendLine(Tabs.Property + "      IsUpdateOrInsert.Add(" + TableName + ".ColumnNames." + this.ProperCase(Column_Name) + ", true); ");
                        PropertiesCode.AppendLine(Tabs.Property + "      this.IsDirty = true; ");
                        PropertiesCode.AppendLine(Tabs.Property + "    }");
                    }
                    else
                    {
                        PropertiesCode.AppendLine(Tabs.Property + "    if (value != " + this.CamelCase(Column_Name) + ")");
                        PropertiesCode.AppendLine(Tabs.Property + "    { ");
                        PropertiesCode.AppendLine(Tabs.Property + "      " + this.CamelCase(Column_Name) + " = value; ");
                        PropertiesCode.AppendLine(Tabs.Property + "      if (!IsUpdateOrInsert.ContainsKey(" + TableName + ".ColumnNames." + this.ProperCase(Column_Name) + "))");
                        PropertiesCode.AppendLine(Tabs.Property + "      IsUpdateOrInsert.Add(" + TableName + ".ColumnNames." + this.ProperCase(Column_Name) + ", true); ");
                        PropertiesCode.AppendLine(Tabs.Property + "      this.IsDirty = true; ");
                        PropertiesCode.AppendLine(Tabs.Property + "    }");
                    }
                    PropertiesCode.AppendLine(Tabs.Property + " }");
                    PropertiesCode.AppendLine(Tabs.SubClass + "}");

                    ColumnNames.AppendLine(Tabs.SubClass + "public const string " + this.ProperCase(Column_Name) + " = \"" + this.ProperCase(Column_Name) + "\";");

                  

                        s_PropertiesCode.AppendLine(" ");
                        s_PropertiesCode.AppendLine(Tabs.SubClass + "///<summary>");
                        s_PropertiesCode.AppendLine(Tabs.SubClass + "///Required = " + required);
                        s_PropertiesCode.AppendLine(Tabs.SubClass + "///DBType = " + dt.ToString());
                        s_PropertiesCode.AppendLine(Tabs.SubClass + "///C# Type = " + dt);
                        s_PropertiesCode.AppendLine(Tabs.SubClass + "///</summary> ");
                        s_PropertiesCode.AppendLine(Tabs.SubClass + "public virtual string s_" + this.ProperCase(Column_Name));
                        s_PropertiesCode.AppendLine(Tabs.SubClass + "{");
                        s_PropertiesCode.AppendLine(Tabs.Property + " get ");
                        s_PropertiesCode.AppendLine(Tabs.Property + " {");
                        s_PropertiesCode.AppendLine(Tabs.Property + "        return Get" + dn.ToString() + "_s(" + this.CamelCase(Column_Name) + ");");
                        s_PropertiesCode.AppendLine(Tabs.Property + " }");
                        s_PropertiesCode.AppendLine(Tabs.Property + " set ");
                        s_PropertiesCode.AppendLine(Tabs.Property + " { ");
                        s_PropertiesCode.AppendLine(Tabs.Property + "        Set" + dn.ToString() + "_s(value, ref " + this.CamelCase(Column_Name) + ");");
                        s_PropertiesCode.AppendLine(Tabs.Property + "      if (!IsUpdateOrInsert.ContainsKey(" + TableName + ".ColumnNames." + this.ProperCase(Column_Name) + "))");
                        s_PropertiesCode.AppendLine(Tabs.Property + "        IsUpdateOrInsert.Add(" + TableName + ".ColumnNames." + this.ProperCase(Column_Name) + ", true);");
                        s_PropertiesCode.AppendLine(Tabs.Property + "        this.IsDirty = true;");
                        s_PropertiesCode.AppendLine(Tabs.Property + " }");
                        s_PropertiesCode.AppendLine(Tabs.SubClass + "}");
                   

                }

                string aaa = FieldsCode.ToString();
                string bbb = PropertiesCode.ToString();
                string ccc = ColumnNames.ToString();
                string ddd = s_PropertiesCode.ToString();

                DataSet ds = new DataSet();
                using (SqlDataAdapter da = new SqlDataAdapter(
                                                              "select top 1 * from [" + TableName + "]",
                                                               cs))
                {
                    da.FillSchema(ds, SchemaType.Mapped);
                }
                if (ds.Tables[0].PrimaryKey.Length > 0)
                {
                    PrimaryKeyName = ds.Tables[0].PrimaryKey[0].ColumnName;
                    PrimaryKeyType = ds.Tables[0].PrimaryKey[0].DataType.ToString();
                }
                int a = 1;
                if (TableName == "test")
                    a = 1;

            }
            catch (Exception) { throw; }
        }

        protected void GetDotNetDataType(ArrayList DataBaseTypes, string SearchAttribute, string SearchValue, ref string DotNetType, ref string DotNetDataBaseType, ref string DefaultValue)
        {
            DataType dt;
            bool Found = false;

            try
            {

                for (int i = 0; i < DataBaseTypes.Count; i++)
                {
                    dt = (DataType)DataBaseTypes[i];

                    if (SearchAttribute == "DataBaseType")
                    {
                        if (dt.DataBaseType == SearchValue)
                        {
                            Found = true;
                        }
                    }

                    if (SearchAttribute == "DotNetType")
                    {
                        if (dt.DotNetType == SearchValue)
                        {
                            Found = true;
                        }
                    }

                    if (SearchAttribute == "DbEnumType")
                    {
                        if (dt.DbEnumType == SearchValue)
                        {
                            Found = true;
                        }
                    }

                    if (!Found) { continue; }

                    DotNetType = dt.DotNetType.Replace(" identity", "");
                    DotNetDataBaseType = dt.DataBaseType.Replace(" identity","");
                    DefaultValue = dt.DefaultValue;
                    return;

                }

                DotNetType = SearchValue.Replace(" identity", "");
                DotNetDataBaseType = SearchValue.Replace(" identity", "");
                DefaultValue = "\"\";";

            }
            catch (Exception) { throw; }

        }

        private DataTable GetColumns(string TableName)
        {
            DataTable oTable = new DataTable();

            try
            {
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    conn.Open();

                    using (SqlCommand cmd = new SqlCommand())
                    {

                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "sp_columns";
                        cmd.Parameters.Add(new SqlParameter("@table_name", SqlDbType.NVarChar, 384));
                        cmd.Parameters["@table_name"].Value = TableName;

                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            da.Fill(oTable);
                        }

                    }

                }
            }
            catch (Exception) { throw; }

            return oTable;
        }

        protected bool IsStandardProperty(string columnName)
        {
            switch (columnName.ToLower().Trim())
            {
                case "sortorder":
                    return true;
                //       case "description":
                //           return true;
                case "isdirty":
                    return true;
                case "isflaggedfordelete":
                    return true;
                default:
                    return false;
            }
        }

        protected class DataType
        {
            public DataType(string pEnumKey,
                            string pDotNetType,
                            string pDataBaseType,
                            string pDbEnumType,
                            string pDefaultValue,
                            bool hasLengthValue)
            {
                this.EnumKey = pEnumKey;
                this.DotNetType = pDotNetType;
                this.DataBaseType = pDataBaseType;
                this.DbEnumType = pDbEnumType;
                this.DefaultValue = pDefaultValue;
                this.HasLengthValue = hasLengthValue;
            }

            public string EnumKey;
            public string DotNetType;
            public string DataBaseType;
            public string DbEnumType;
            public string DefaultValue;
            public bool HasLengthValue;
        }

        public string CamelCase(string inputVal)
        {
            string Ret = inputVal.Trim();
            try
            {
                if (Ret.Length < 2) { return Ret.ToLower(); }
                Ret = Ret.Substring(0, 1).ToLower() + Ret.Substring(1, Ret.Length - 1);
            }
            catch (Exception) { throw; }
            Ret = replace_tr_chars_to_en(Ret);

            return Ret;
        }

        public string ProperCase(string inputVal)
        {
            string Ret = inputVal.Trim();
            try
            {
                if (Ret.Length < 2)
                {
                    return Ret.ToLower();
                }
                Ret = Ret.Substring(0, 1).ToUpper() + Ret.Substring(1, Ret.Length - 1);
            }
            catch (Exception)
            {
                throw;
            }
            Ret = replace_tr_chars_to_en(Ret);
            return Ret;
        }

        public string replace_tr_chars_to_en(string val)
        {
            string newvalue = string.Empty;

            foreach (var item in val)
            {
                if (item == 'ı') newvalue += "i";
                else if (item == 'İ') newvalue += "I";
                else if (item == 'ğ') newvalue += "g";
                else if (item == 'Ğ') newvalue += "G";
                else if (item == 'ü') newvalue += "u";
                else if (item == 'Ü') newvalue += "U";
                else if (item == 'ş') newvalue += "s";
                else if (item == 'Ş') newvalue += "S";
                else if (item == 'ö') newvalue += "O";
                else if (item == 'Ö') newvalue += "O";
                else if (item == 'ç') newvalue += "c";
                else if (item == 'Ç') newvalue += "C";
                else newvalue += item.ToString();
            }
            return newvalue;
        }

        protected void LoadDataTypes()
        {
            try
            {
                SqlDataTypes.Add(new DataType("11", "bool", "bit", "SqlDbType.Bit", "false;", false));                
                SqlDataTypes.Add(new DataType("", "byte[]", "binary", "SqlDbType.Binary", "null;", false));
                SqlDataTypes.Add(new DataType("", "Int64", "bigint", "SqlDbType.BigInt", "-1;", false));
                SqlDataTypes.Add(new DataType("", "Int64", "bigint identity", "SqlDbType.BigInt", "-1;", false));                
                SqlDataTypes.Add(new DataType("", "string", "char", "SqlDbType.Char", "string.Empty;", true));
                SqlDataTypes.Add(new DataType("", "DateTime", "datetime", "SqlDbType.DateTime", "new DateTime();", false));
                SqlDataTypes.Add(new DataType("", "DateTime", "date", "SqlDbType.Date", "new DateTime();", false));
                SqlDataTypes.Add(new DataType("", "DateTime", "datetime2", "SqlDbType.DateTime2", "new DateTime();", false));
                SqlDataTypes.Add(new DataType("", "DateTimeOffset", "datetimeoffset", "SqlDbType.DateTimeOffset", "new DateTime();", false));
                SqlDataTypes.Add(new DataType("", "decimal", "decimal", "SqlDbType.Decimal", "-1;", false));
                SqlDataTypes.Add(new DataType("", "double", "float", "SqlDbType.Float", "-1;", false));
                SqlDataTypes.Add(new DataType("", "byte[]", "image", "SqlDbType.Image", "null;", false));                
                SqlDataTypes.Add(new DataType("", "Int32", "int", "SqlDbType.Int", "-1;", false));
                SqlDataTypes.Add(new DataType("", "Int32", "int identity", "SqlDbType.Int", "-1;", false));
                SqlDataTypes.Add(new DataType("", "decimal", "money", "SqlDbType.Money", "-1;", false));
                SqlDataTypes.Add(new DataType("", "string", "nchar", "SqlDbType.NChar", "string.Empty;", true));
                SqlDataTypes.Add(new DataType("", "string", "ntext", "SqlDbType.NText", "string.Empty;", false));
                SqlDataTypes.Add(new DataType("", "string", "nvarchar", "SqlDbType.NVarChar", "string.Empty;", true));
                SqlDataTypes.Add(new DataType("", "decimal", "numeric", "SqlDbType.Decimal", "-1;", false));
                SqlDataTypes.Add(new DataType("", "Single", "real", "SqlDbType.Real", "-1;", false));
                SqlDataTypes.Add(new DataType("", "DateTime", "smalldatetime", "SqlDbType.SmallDateTime", "new DateTime();", false));
                SqlDataTypes.Add(new DataType("", "Int16", "smallint", "SqlDbType.SmallInt", "-1;", false));
                SqlDataTypes.Add(new DataType("", "Int16", "smallint identity", "SqlDbType.SmallInt", "-1;", false));
                SqlDataTypes.Add(new DataType("", "decimal", "smallmoney", "SqlDbType.SmallMoney", "-1;", false));
                SqlDataTypes.Add(new DataType("", "object", "sql_variant", "SqlDbType.Variant", "null;", false));
                SqlDataTypes.Add(new DataType("", "string", "xml", "SqlDbType.Xml", "string.Empty;", false));

                SqlDataTypes.Add(new DataType("", "string", "sysname", "SqlDbType.NVarChar", "string.Empty;", true));
                SqlDataTypes.Add(new DataType("", "string", "text", "SqlDbType.Text", "string.Empty;", false));
                SqlDataTypes.Add(new DataType("", "TimeSpan", "time", "SqlDbType.TimeSpan", " new TimeSpan();", false));
                SqlDataTypes.Add(new DataType("", "DateTime", "timestamp", "SqlDbType.Timestamp", "new DateTime();", false));
                SqlDataTypes.Add(new DataType("", "byte", "tinyint", "SqlDbType.TinyInt", "0;", false));
                SqlDataTypes.Add(new DataType("", "byte", "tinyint identity", "SqlDbType.TinyInt", "0;", false));
                SqlDataTypes.Add(new DataType("", "byte[]", "varbinary", "SqlDbType.VarBinary", "null;", false));
                SqlDataTypes.Add(new DataType("", "string", "varchar", "SqlDbType.VarChar", "string.Empty;", true));
                SqlDataTypes.Add(new DataType("", "Guid", "uniqueidentifier", "SqlDbType.UniqueIdentifier", "Guid.Empty;", false));
            }
            catch (Exception) { throw; }

        }

        public bool WriteToFile(string FileName, string temp)
        {
            try
            {
                if (string.IsNullOrEmpty(temp)) { return false; }

                using (StreamWriter s = new StreamWriter(FileName, false))
                {
                    s.Write(temp);
                    s.Close();
                    if (File.Exists(FileName)) { return true; }
                }
            }
            catch (Exception) { return false; }
            return true;
        }
    }
}
